import { Injectable } from '@angular/core';
import { HttpErrorResponse} from "@angular/common/http";
import { CustomToastProviderService,CustomToastOption } from '@common-components/common-toast/custom-toast-provider.service';
import { TranslateService } from '@ngx-translate/core';

@Injectable({
  providedIn: 'root'
})

export class CommonMethodService {

    private commonInterceptorErrorCode:Array<string> = ['user_token_expired','invalid_token','verification_failed','device_changed'];

    constructor(private customToastProviderService:CustomToastProviderService,
                private translate:TranslateService) { }

    geti18n(modules:Array<string>){
        let i18n = {};
        modules.push('common_verification');
        this.translate.get(modules).subscribe((jsons)=>{
            for(var item in jsons){
                i18n = Object.assign(i18n,jsons[item]);
            }
        });
        return i18n;
    }

    errorRespCommonToastForInterceptor(httpErrorResp:HttpErrorResponse,i18n?:Object,duration?:number){ 
        this.errorRespCommonToast(httpErrorResp,true,i18n,duration);
    }
    
    errorRespCommonToast(httpErrorResp:HttpErrorResponse,isInterceptor:boolean=false,i18n?:Object,duration?:number){ 
        let errorMsg = '';
        let errorCode = '';
        if(!i18n){
            i18n = this.geti18n([]);
        }
        if(httpErrorResp.error && httpErrorResp.error.errorCode){
            errorCode = httpErrorResp.error.errorCode;
            errorMsg = i18n.hasOwnProperty(errorCode)?i18n[errorCode]:httpErrorResp.error.errorMsg;
        }else{
            errorCode = 'operate_failed';
            errorMsg = i18n[errorCode];
        }
        
        if(!isInterceptor && this.commonInterceptorErrorCode.indexOf(errorCode)>-1){
            return false;
        }

        let customToastOption:CustomToastOption = {
            icon:false,
            iconSuccess:false,
            message:errorMsg,
            duration:duration?duration:2000
        }
        this.customToastProviderService.show(customToastOption);
    }

}